package com.info.zhiduoduo.core.service.wxmessage;

import com.baomidou.mybatisplus.mapper.Condition;
import com.info.zhiduoduo.common.configs.CommonConfig;
import com.info.zhiduoduo.common.configs.NotificationConfig;
import com.info.zhiduoduo.common.configs.PayConfig;
import com.info.zhiduoduo.common.configs.RechargeNotifyConfig;
import com.info.zhiduoduo.common.configs.ZddUrlConfig;
import com.info.zhiduoduo.common.constants.system.UserType;
import com.info.zhiduoduo.common.constants.email.EmailType;
import com.info.zhiduoduo.common.constants.project.ProjectType;
import com.info.zhiduoduo.common.utils.ContextUtil;
import com.info.zhiduoduo.common.utils.DateUtil;
import com.info.zhiduoduo.common.utils.NumberUtil;
import com.info.zhiduoduo.repository.dto.company.CompanyRechargeDto;
import com.info.zhiduoduo.repository.dto.maker.MakerDetailDto;
import com.info.zhiduoduo.repository.dto.partner.PartnerDetailDto;
import com.info.zhiduoduo.repository.entity.company.Company;
import com.info.zhiduoduo.repository.entity.company.CompanyAccount;
import com.info.zhiduoduo.repository.entity.company.CompanyAuthRecord;
import com.info.zhiduoduo.repository.entity.company.CompanyOfflineRechargeDetail;
import com.info.zhiduoduo.repository.entity.company.CompanyProject;
import com.info.zhiduoduo.repository.entity.company.CompanyRecharge;
import com.info.zhiduoduo.repository.entity.invoice.Invoice;
import com.info.zhiduoduo.repository.entity.maker.Maker;
import com.info.zhiduoduo.repository.entity.maker.MakerAccount;
import com.info.zhiduoduo.repository.entity.maker.MakerAuthRecord;
import com.info.zhiduoduo.repository.entity.maker.MakerStudio;
import com.info.zhiduoduo.repository.entity.order.TradeRecord;
import com.info.zhiduoduo.repository.entity.taxer.TaxerInvoice;
import com.info.zhiduoduo.repository.entity.weixin.WxNotice;
import com.info.zhiduoduo.repository.mapper.company.CompanyRechargeMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerMapper;
import com.info.zhiduoduo.repository.mapper.maker.MakerStudioMapper;
import com.info.zhiduoduo.repository.mapper.order.TradeRecordMapper;
import com.info.zhiduoduo.wxsdk.WxApiService;
import com.info.zhiduoduo.wxsdk.config.WxTaxerConfig;
import com.info.zhiduoduo.wxsdk.domain.app.WxTempleteMessage;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.RoundingMode;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

@Service("wxTaxerMessageService")
public class WxTaxerWxMessageServiceImpl extends BaseWxMessageService {

    @Autowired
    WxApiService wxApiService;

    @Autowired
    TradeRecordMapper tradeRecordMapper;
    @Autowired
    MakerStudioMapper makerStudioMapper;
    @Autowired
    MakerMapper makerMapper;
    @Autowired
    CompanyRechargeMapper companyRechargeMapper;

    @Autowired
    RechargeNotifyConfig rechargeNotifyConfig;
    @Autowired
    PayConfig payConfig;
    @Autowired
    CommonConfig commonConfig;
    @Autowired
    WxTaxerConfig wxTaxerConfig;
    @Autowired
    ZddUrlConfig zddUrlConfig;
    @Autowired
    NotificationConfig notificationConfig;

    /**
     * 专门测试用的, 使用一个通用模板
     */
    private static final String TEMP_TEST = "BlUjsCpze1iDbeeGwTCovrAdCBa9m7eHMlUkH42Hfcw";
    /**
     * 流程确认通知
     */
    private static final String TEMP_PROCESS_CONFIRM = "-Sp7PhN6NBaVcvrizHd0Hz4QlVeBVt4VJmS8NKaab5I";
    /**
     * 回款到账通知
     */
    private static final String TEMP_IN_ACCOUNT_CHECKED = "Q_rK3doBWHoxFTp6vIEY2PSN5cWZGgvgPkxBpQ9nCt4";
    /**
     * 业务状态变更通知
     */
    private static final String TEMP_STATE_CHANGED = "nnSlj5AT8aBzLF5KvZK3QqiUXeWkrzCsuzmkWMvoIwc";
    /**
     * 认证通知
     */
    private static final String TEMP_AUTH_NOTIFY = "QNKfN8E5ar47UwHe88gqzXIugEtHSpxduW5I_sgCrzs";
    /**
     * 验证码通知
     */
    private static final String TEMP_VERIFYCODE = "mFDPY6_UgFiS5fiGylS8bv5wx0Fw0wRhDaeerGhKP4A";
    /**
     * 验证码通知
     */
    private static final String TEMP_RECHARGE = "aqwWfk_x5cT4CC6vNhV0zKsjJUgVd1p-DZhBGsZ51M4";
    /**
     * 公告通知
     */
    private static final String TEMP_SEND_NOTICE = "ov7xAm6KUr22hufLpScOoOFgan1RH8OLYGBlnq7F5f4";
    /**
     * 问卷调查公告通知
     */
    private static final String TEMP_SURVEY_NOTICE = "vKSV5smmI5h9zd4mxRyIVyu4FMqqCQJu1MyEwso7gZs";
    /**
     * 发票开票成功通知
     */
    public static final String TEMP_INVOICE_NOTICE = "-cjO4-WJXTqT3OpgKmYv8UfeS-BuynnZdglzkIoOePE";

    /**
     * 智杰祱公众号 问卷调查通知
     */
    public static final String TEMP_QUESTIONNAIRE = "0dncQ9-PEV5m-mIZ648G1qZyD2NNll7rkJ0tbvLqjFg";
    /**
     * 智杰祱公众号 业务处理结果通知
     */
    public static final String TEMP_HANDLE = "EoubahIFlIZl709m-fw6IjSghrqjE9XQTVky6huaTew";

    // 用户注册审核通知
    public static final String AUTH_NOTIFY_TEMPLATE = "rfc-acIEynIHLihYsxODAhU6cpHVWyq0w1IoheepK_k";
    // 用户注册成功通知
    public static final String REGISTER_NOTIFY_TEMPLATE = "P_s2UdpLeucmaVvoGwUd3AQZQ4836suw307y0Z2Lz4o";
    // 发票开具成功通知
    public static final String INVOICE_NOTIFY_TEMPLATE = "7g8OmcbCPoOJNLTKXdZ-HduMG8qkOx7NFVF-LzJU3kU";
    // 发票开局成功通知
//    public static final String INVOICE_NOTIFY_TEMPLATE = "";

    ExecutorService executor;

    public WxTaxerWxMessageServiceImpl() {
        this.executor = Executors.newSingleThreadExecutor();
    }

    /**
     * 发送模板消息,如果直接在当前线程发送会堵塞当前线程,造成服务器与前端交互等待时间太长,所以这里采用线程executor,单独执行
     *
     * @param message
     * @return
     */
    private Future sendMessage(WxTempleteMessage message, String name, Integer type, String templateId, Integer userId) {
        if (type != null) {
            String first = "";
            String remark = "";
            String str = "";

            Map<String, WxTempleteMessage.ValueColor> data = message.getData();
            Iterator<Map.Entry<String, WxTempleteMessage.ValueColor>> iterator = data.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, WxTempleteMessage.ValueColor> next = iterator.next();
                String key = next.getKey();
                if (key.equals("first")) {
                    first = next.getValue().getValue();
                } else if (key.equals("remark")) {
                    remark = next.getValue().getValue();
                } else {
                    str += next.getValue().getValue();
                }
            }
            new WxNotice().setNoticeType(type)
                    .setNoticePeople(name)
                    .setNoticeTitle(first)
                    .setNoticeRemarks(remark)
                    .setNoticeContent(str)
                    .setNoticeTemplate(templateId)
                    .setUserId(userId)
                    .insert();
        }
        return executor.submit(() -> {
            wxApiService.sendTempleteMessage(message, wxTaxerConfig.getAppid(), wxTaxerConfig.getSecret());
        });
    }

    @Override
    public boolean notifyUserProjectPublish(int projectid) {

        CompanyProject project = new CompanyProject().selectById(projectid);
        if (project == null) return false;

        Maker maker = new Maker().selectById(project.getUserid());
        if (maker == null) return false;
        MakerAccount account = new MakerAccount().selectOne(Condition.create().eq("userid", maker.getUserid()));
        if (null == account) return false;
        MakerStudio makerStudio = new MakerStudio().selectById(project.getUserid());
        if (makerStudio == null) return false;

        Company company = new Company().selectById(project.getCompid());
        if (company == null) return false;

        String openid = maker.getOpenid();
		/*
		标题业务状态变更通知
		行业IT科技 - 互联网|电子商务
		详细内容{{first.DATA}}
		变更类型：{{keyword1.DATA}}
		变更结果：{{keyword2.DATA}}
		变更时间：{{keyword3.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(TEMP_STATE_CHANGED);
        message.setUrl(String.format(commonConfig.getProjectDetailUrl(), projectid));
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first",
                WxTempleteMessage.ValueColor.of("企业-" + company.getCompname() + "发布了一个新项目给您:" + project.getProjectname(), "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of("项目进度更新"));
        data.put("keyword2", WxTempleteMessage.ValueColor.of("项目发布成功,请尽快完成。 "));
        data.put("keyword3", WxTempleteMessage.ValueColor.of(DateUtil.getString(new Date(), DateUtil.FORMAT_STYLE_6)));
        data.put("remark", WxTempleteMessage.ValueColor.of(""));
        message.setData(data);

        sendMessage(message, account.getRealname(), EmailType.MAKER, TEMP_STATE_CHANGED, account.getUserid());
        return true;
    }

    @Override
    public boolean notifyCompanyProjectCheck(int projectid) {

        CompanyProject project = new CompanyProject().selectById(projectid);
        if (project == null) return false;

        MakerStudio makerStudio = new MakerStudio().selectById(project.getUserid());
        if (makerStudio == null) return false;

        Company company = new Company().selectById(project.getCompid());
        if (company == null) return false;
        CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", company.getCompid()));
        if (companyAccount == null) return false;
        String openid = company.getOpenid();
		/*
		标题业务状态变更通知
		行业IT科技 - 互联网|电子商务
		详细内容{{first.DATA}}
		变更类型：{{keyword1.DATA}}
		变更结果：{{keyword2.DATA}}
		变更时间：{{keyword3.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(TEMP_STATE_CHANGED);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first",
                WxTempleteMessage.ValueColor.of("创客-" + makerStudio.getUsername() + "通知您验收项目:" + project.getProjectname(), "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of("项目进度更新"));
        data.put("keyword2", WxTempleteMessage.ValueColor.of("创客完成项目,等待验收。"));
        data.put("keyword3", WxTempleteMessage.ValueColor.of(DateUtil.getString(new Date(), DateUtil.FORMAT_STYLE_6)));
        data.put("remark", WxTempleteMessage.ValueColor.of(""));
        message.setData(data);
        sendMessage(message, company.getCompname(), EmailType.COMP, TEMP_STATE_CHANGED, company.getCompid());
        return true;
    }

    @Override
    public boolean notifyUserProjectPassed(int projectid) {

        CompanyProject project = new CompanyProject().selectById(projectid);
        if (project == null) return false;

        MakerStudio makerStudio = new MakerStudio().selectById(project.getUserid());
        if (makerStudio == null) return false;

        Company company = new Company().selectById(project.getCompid());
        if (company == null) return false;

        Integer userid = project.getUserid();
        Maker maker = new Maker().selectById(userid);
        if (maker == null) return false;
        MakerAccount account = new MakerAccount().selectOne(Condition.create().eq("userid", maker.getUserid()));
        if (null == account) return false;
        String openid = maker.getOpenid();
		/*
		标题业务状态变更通知
        行业IT科技 - 互联网|电子商务
        详细内容{{first.DATA}}
        变更类型：{{keyword1.DATA}}
        变更结果：{{keyword2.DATA}}
        变更时间：{{keyword3.DATA}}
        {{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(TEMP_STATE_CHANGED);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of(company.getCompname() + "已经验收通过项目:" + project.getProjectname(), "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of("项目进度更新"));
        data.put("keyword2", WxTempleteMessage.ValueColor.of("企业验收通过"));
        data.put("keyword3", WxTempleteMessage.ValueColor.of(DateUtil.getString(new Date(), DateUtil.FORMAT_STYLE_6)));
        data.put("remark", WxTempleteMessage.ValueColor.of(""));
        message.setData(data);

        sendMessage(message, account.getRealname(), EmailType.MAKER, TEMP_STATE_CHANGED, account.getUserid());
        return true;
    }

    @Override
    public boolean notifyMakerEvaluate(int invoiceid) {
        TaxerInvoice invoice = new TaxerInvoice().selectById(invoiceid);
        if (invoice == null) return false;
        Integer userid = invoice.getUserid();
        Maker maker = new Maker().selectById(userid);
        if (null == maker) return false;
        MakerAccount account = new MakerAccount().selectOne(Condition.create().eq("userid", maker.getUserid()));
        if (null == account) return false;
        //判断创客是否评价过，如果评价过则不发送通知
        if (0 != account.getWhetherEvaluate()) return false;

        String url = String.format(zddUrlConfig.getTaxerEvaluateUrl(), invoice.getUserid(), UserType.TAXER, invoice.getCompanyid(),
                ProjectType.TAXER);
        String openid = maker.getTaxerOpenid();
		/*
		标题认证通知
		行业IT科技 - 互联网|电子商务
		详细内容{{first.DATA}}
		认证详情：{{keyword1.DATA}}
		认证结果：{{keyword2.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setUrl(url);
        message.setTemplate_id(TEMP_STATE_CHANGED);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of("您好，恭喜您交易成功，平台邀请您对本次交易进行评价！", "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of("交易完成"));
        data.put("keyword2", WxTempleteMessage.ValueColor.of("邀请评价"));
        data.put("keyword3", WxTempleteMessage.ValueColor.of(DateUtil.DateToStr(DateUtil.FORMAT_STYLE_6, new Date())));
        data.put("remark", WxTempleteMessage.ValueColor.of(""));
        message.setData(data);
        sendMessage(message, account.getRealname(), EmailType.TAXER_MAKER, TEMP_STATE_CHANGED, account.getUserid());
        return true;
    }

    @Override
    public boolean notifyUserCompanyProjectArbitrate(int projectid) {
        CompanyProject project = new CompanyProject().selectById(projectid);
        if (project == null) return false;

        Company company = new Company().selectById(project.getCompid());
        if (company == null) return false;
        CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", company.getCompid()));
        if (companyAccount == null) return false;
        //发送给创客
        Integer userid = project.getUserid();
        Maker maker = new Maker().selectById(userid);
        if (maker == null) return false;
        MakerAccount account = new MakerAccount().selectOne(Condition.create().eq("userid", maker.getUserid()));
        if (null == account) return false;
        String openid = maker.getOpenid();

		/*
		标题业务状态变更通知
		行业IT科技 - 互联网|电子商务
		详细内容{{first.DATA}}
		变更类型：{{keyword1.DATA}}
		变更结果：{{keyword2.DATA}}
		变更时间：{{keyword3.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(TEMP_STATE_CHANGED);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of(project.getProjectname() + "已经通过智多平台仲裁!", "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of("项目进度更新"));
        data.put("keyword2",
                WxTempleteMessage.ValueColor.of("平台仲裁金额为" + project.getProjectdealamount().setScale(2, RoundingMode.DOWN).toString()));
        data.put("keyword3", WxTempleteMessage.ValueColor.of(DateUtil.getString(new Date(), DateUtil.FORMAT_STYLE_6)));
        data.put("remark", WxTempleteMessage.ValueColor.of(""));
        message.setData(data);

        sendMessage(message, account.getRealname(), EmailType.MAKER, TEMP_STATE_CHANGED, account.getUserid());

        //--------发送给企业-------

        String openidComp = company.getOpenid();
		/*
		标题业务状态变更通知
		行业IT科技 - 互联网|电子商务
		详细内容{{first.DATA}}
		变更类型：{{keyword1.DATA}}
		变更结果：{{keyword2.DATA}}
		变更时间：{{keyword3.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage messageComp = new WxTempleteMessage();
        messageComp.setTouser(openidComp);
        messageComp.setTemplate_id(TEMP_STATE_CHANGED);
        Map<String, WxTempleteMessage.ValueColor> dataComp = new HashMap<>();
        dataComp.put("first", WxTempleteMessage.ValueColor.of(project.getProjectname() + "已经通过智多平台仲裁!", "#000000"));
        dataComp.put("keyword1", WxTempleteMessage.ValueColor.of("项目进度更新"));
        dataComp.put("keyword2",
                WxTempleteMessage.ValueColor.of("平台仲裁金额为" + project.getProjectdealamount().setScale(2, RoundingMode.DOWN).toString()));
        dataComp.put("keyword3", WxTempleteMessage.ValueColor.of(DateUtil.getString(new Date(), DateUtil.FORMAT_STYLE_6)));
        dataComp.put("remark", WxTempleteMessage.ValueColor.of(""));
        messageComp.setData(dataComp);

        sendMessage(messageComp, company.getCompname(), EmailType.COMP, TEMP_STATE_CHANGED, company.getCompid());
        return true;
    }

    @Override
    public boolean notifyAdminPaymentFail(TradeRecord trade) {

        CompanyProject project = new CompanyProject().selectById(trade.getProjectid());
        if (project == null) return false;

        Company company = new Company().selectById(project.getCompid());
        if (company == null) return false;

        MakerStudio studio = new MakerStudio().selectById(project.getUserid());
        if (studio == null) return false;

        //通知给指定的人
        Map<String, String> payFailedNotifyOpenids = payConfig.getPayFailedNotifyOpenids();

		/*
		标题业务状态变更通知
		行业IT科技 - 互联网|电子商务
		详细内容{{first.DATA}}
		变更类型：{{keyword1.DATA}}
		变更结果：{{keyword2.DATA}}
		变更时间：{{keyword3.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTemplate_id(TEMP_STATE_CHANGED);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of(
                "项目款代付交易失败通知！" + "\n企业名：" + company.getCompname() + "\n创客名：" + studio.getUsername() + "\n项目名：" + project.getProjectname() +
                        "\n交易编号：" + trade.getTradeno() + "\n交易金额：" + trade.getTradeamount(), "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of((trade.getTradestate() == 4 ? "交易失败" : "交易拒绝")));
        data.put("keyword2", WxTempleteMessage.ValueColor.of("ErrorCode=" + trade.getErrorcode() + " ,ErrorMsg=" + trade.getErrormsg()));
        data.put("keyword3", WxTempleteMessage.ValueColor.of(DateUtil.getString(trade.getFinishtime(), DateUtil.FORMAT_STYLE_6)));
        data.put("remark", WxTempleteMessage.ValueColor.of(""));
        message.setData(data);

        //		openids.stream().map(openid -> {
        //			WxTempleteMessage msg = new WxTempleteMessage();
        //			BeanUtils.copyProperties(message, msg);
        //			msg.setTouser(openid);
        //			return msg;
        //		}).forEach(this::sendMessage);

        Set<String> strings = payFailedNotifyOpenids.keySet();
        Iterator<String> iterator = strings.iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            WxTempleteMessage msg = new WxTempleteMessage();
            BeanUtils.copyProperties(message, msg);
            msg.setTouser(payFailedNotifyOpenids.get(next));
            sendMessage(msg, next, EmailType.OTHER, TEMP_STATE_CHANGED, null);
        }

        return true;
    }

    @Override
    public boolean notifyCompanyRecharged(int rechargeid) {

        CompanyRecharge recharge = new CompanyRecharge().selectById(rechargeid);
        if (recharge == null) return false;

        Company company = new Company().selectById(recharge.getCompid());
        if (company == null) return false;
        CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", company.getCompid()));
        if (companyAccount == null) return false;
        String openid = company.getOpenid();
/*
		详细内容
		{{first.DATA}}
		会员账号：{{keyword1.DATA}}  这里可以显示公司名字
		充值金额：{{keyword2.DATA}}
		充值订单：{{keyword3.DATA}}  这里可以显示回单唯一ID
		充值时间：{{keyword4.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(TEMP_RECHARGE);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of("充值入账成功通知", "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of(company.getCompname()));
        data.put("keyword2", WxTempleteMessage.ValueColor.of(recharge.getAmount().setScale(2, RoundingMode.DOWN).toString()));
        data.put("keyword3", WxTempleteMessage.ValueColor.of(recharge.getReceiptno()));
        data.put("keyword4", WxTempleteMessage.ValueColor.of(DateUtil.getString(recharge.getRechargetime(), DateUtil.FORMAT_STYLE_6)));
        data.put("remark", WxTempleteMessage.ValueColor.of("请注意核对,谢谢!"));
        message.setData(data);

        sendMessage(message, company.getCompname(), EmailType.COMP, TEMP_RECHARGE, company.getCompid());
        return true;
    }

    @Override
    public boolean notifyCompanyOfflineRecharged(CompanyOfflineRechargeDetail rechargeid) {
        return false;
    }

    @Override
    public boolean userAuthState(int acctid) {

        MakerAccount makerAccount = new MakerAccount().selectById(acctid);
        if (makerAccount == null) return false;

        Maker maker = new Maker().selectById(makerAccount.getUserid());
        if (maker == null) return false;

        MakerAuthRecord record = new MakerAuthRecord().selectOne(
                Condition.create().eq("acctid", acctid).orderBy("id", false).last("limit 1"));

        String remark = "";
        switch (record.getState()) {
            case 1:
                remark = "审核失败"; //,原因-" + record.getReason() + "\n请重新提交审核资料,谢谢
                break;
            case 0:
                remark = "审核通过";
                break;
            default:
                remark = "";

        }

        String openid = maker.getTaxerOpenid();
/*
		{{first.DATA}}
		姓名：{{keyword1.DATA}}
		手机号：{{keyword2.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(AUTH_NOTIFY_TEMPLATE);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of("用户注册审核通知", "#000000"));
        data.put("thing2", WxTempleteMessage.ValueColor.of(makerAccount.getRealname()));
        data.put("time5", WxTempleteMessage.ValueColor.of(DateUtil.getString(maker.getCreatetime())));
        data.put("const4", WxTempleteMessage.ValueColor.of(remark));
        message.setData(data);

        sendMessage(message, makerAccount.getRealname(), EmailType.MAKER, AUTH_NOTIFY_TEMPLATE, makerAccount.getUserid());
        return true;
    }

    @Override
    public boolean userStudioConfirmed(int userid) {

        MakerDetailDto maker = makerMapper.getUserDetail(userid);
        if (maker == null) return false;
        String openid = maker.getTaxerOpenid();
        MakerAccount account = new MakerAccount().selectOne(Condition.create().eq("userid", maker.getUserid()));
        if (null == account) return false;
/*
		{{first.DATA}}
		姓名：{{keyword1.DATA}}
		手机号：{{keyword2.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(REGISTER_NOTIFY_TEMPLATE);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of("用户注册成功通知", "#000000"));
        data.put("thing19", WxTempleteMessage.ValueColor.of(maker.getRealname()));
        data.put("thing14", WxTempleteMessage.ValueColor.of(maker.getUsername()));
        message.setData(data);

        sendMessage(message, account.getRealname(), EmailType.TAXER_MAKER, REGISTER_NOTIFY_TEMPLATE, account.getUserid());
        return true;
    }

    @Override
    public boolean compAuthState(int compid) {

        Company company = new Company().selectById(compid);
        if (company == null) return false;
        CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", company.getCompid()));
        if (companyAccount == null) return false;
        CompanyAuthRecord record = new CompanyAuthRecord().selectOne(
                Condition.create().eq("compid", compid).orderBy("id", false).last("limit 1"));

        String authResult;
        String remark = "";
        switch (record.getState()) {
            case 1:
                authResult = "审核失败,原因-" + record.getReason();
                remark = "请重新提交审核资料,谢谢";
                break;
            case 0:
                authResult = "审核通过!";
                break;
            default:
                authResult = "";

        }

        String openid = company.getOpenid();
/*
		标题认证通知
		行业IT科技 - 互联网|电子商务
		详细内容{{first.DATA}}
		认证详情：{{keyword1.DATA}}
		认证结果：{{keyword2.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(TEMP_AUTH_NOTIFY);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of("企业实名认证审核通知", "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of("企业名-" + company.getCompname()));
        data.put("keyword2", WxTempleteMessage.ValueColor.of(authResult));
        data.put("remark", WxTempleteMessage.ValueColor.of(remark));
        message.setData(data);

        sendMessage(message, company.getCompname(), EmailType.COMP, TEMP_AUTH_NOTIFY, company.getCompid());

        if (record.getState() == 0) {
            //审核通过，通知胡刚
            WxTempleteMessage msg = new WxTempleteMessage();
            BeanUtils.copyProperties(message, msg);
            msg.setTouser(notificationConfig.getBossOpenid());
            sendMessage(msg, "胡刚", EmailType.OTHER, TEMP_AUTH_NOTIFY, null);
        }
        return true;
    }

    @Override
    public boolean sendVerifycode(int rechargeid, String verifycode) {

        CompanyRechargeDto recharge = companyRechargeMapper.getRechargeDetail(rechargeid);
        if (recharge == null) return false;

        String openid = rechargeNotifyConfig.getOpenid();
/*
		标题验证码通知
		行业IT科技 - 互联网|电子商务
		详细内容{{first.DATA}}
		验证码：{{keyword1.DATA}}
		通知时间：{{keyword2.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(TEMP_VERIFYCODE);
        message.setUrl(rechargeNotifyConfig.getDetailurl() + rechargeid);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of(recharge.getCompname() + " 充值确认验证码", "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of(verifycode));
        data.put("keyword2", WxTempleteMessage.ValueColor.of(DateUtil.getString(new Date(), DateUtil.FORMAT_STYLE_6)));
        data.put("remark", WxTempleteMessage.ValueColor.of("验证码在十分钟内有效"));
        message.setData(data);

        sendMessage(message, "管理员", EmailType.OTHER, TEMP_VERIFYCODE, null);
        return true;
    }

    @Override
    public boolean sendOfflineVerifycode(int rechargeid, String verifycode) {
        return false;
    }

    @Override
    public boolean sendNotice(String title, String url, String openid) {

		/*
		标题业务处理结果通知
		行业IT科技 - 互联网|电子商务
		详细内容{{first.DATA}}
		系统名称：{{keyword1.DATA}}
		完成时间：{{keyword2.DATA}}
		结果描述：{{keyword3.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(TEMP_SEND_NOTICE);
        message.setUrl(url);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of(" 平台公告", "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of(title));
        data.put("keyword2", WxTempleteMessage.ValueColor.of(DateUtil.getNowTimeString()));
        data.put("keyword3", WxTempleteMessage.ValueColor.of("请点击查看详情"));
        message.setData(data);

        sendMessage(message, null, null, TEMP_SEND_NOTICE, null);
        return true;
    }

    @Override
    public boolean sendInvoiceNotice(int invoiceid, int toType) {

        Invoice invoice = new Invoice().selectById(invoiceid);
        if (invoice == null) return false;

        Maker maker = new Maker().selectById(invoice.getUserid());
        Company company = new Company().selectById(invoice.getCompid());

        if (maker == null) return false;
        if (company == null) return false;

        MakerStudio makerStudio = new MakerStudio().selectById(invoice.getUserid());

        String openid;
        String title;
        String invoiceName;
        String keyword3;
        String name;
        Integer type;
        Integer userId;
        if (invoice.getInvoicetype() == 1) {
            invoiceName = "电子普票";
            keyword3 = "电子普票已发送至" + invoice.getEmail();
        } else if (invoice.getInvoicetype() == 2) {
            invoiceName = "纸质专票";
            keyword3 = "纸质发票已寄出，快递信息为：" + invoice.getExpress() + "," + invoice.getExpressno();
        } else {
            return false;
        }

        if (toType == 1) {
            MakerAccount account = new MakerAccount().selectOne(Condition.create().eq("userid", maker.getUserid()));
            if (null == account) return false;
            name = account.getRealname();
            type = EmailType.MAKER;
            userId = account.getUserid();
            openid = maker.getOpenid();
            title = "您已成功为" + company.getCompname() + "开具" + invoiceName + "，具体明细如下：";
        } else if (toType == 2) {
            CompanyAccount companyAccount = new CompanyAccount().selectOne(Condition.create().eq("compid", company.getCompid()));
            if (companyAccount == null) return false;
            name = companyAccount.getRealname();
            type = EmailType.COMP;
            userId = company.getCompid();
            openid = company.getOpenid();
            title = makerStudio.getUsername() + "已成功为您开具" + invoiceName + "，具体明细如下：";
        } else {
            return false;
        }
        String keyword1 = "【项目名称】" + invoice.getProjectname() + "\n【票种】" + invoice.getContent() + "\n【金额】" +
                NumberUtil.formatFloat2_0(invoice.getInvoiceAmount().floatValue()) + "元";

		/*
		XX创客工作室已成功为您开具电子普票/纸质专票，具体明细如下：
		{{first.DATA}}
		系统名称：【票种】服务费?/咨询费？【金额】XX元【项目名称】？？{{keyword1.DATA}}
		完成时间：{{keyword2.DATA}}
		结果描述：【邮箱】已发送至XXXX  {{keyword3.DATA}}
		感谢您使用 平台，期待为您的再次服务
		如有疑问，您可致电我们的全国客服电话：17710090008   {{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(TEMP_INVOICE_NOTICE);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of(title, "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of(keyword1));
        data.put("keyword2", WxTempleteMessage.ValueColor.of(DateUtil.getNowTimeString()));
        data.put("keyword3", WxTempleteMessage.ValueColor.of(keyword3));
        data.put("remark", WxTempleteMessage.ValueColor.of("如有疑问，您可致电平台全国客服电话：17710090008 "));
        message.setData(data);

        sendMessage(message, name, type, TEMP_INVOICE_NOTICE, userId);
        return true;
    }

    /**
     *  发票开票成功
     *
     * @param invoiceid
     * @return
     */
    @Override
    public boolean sendTaxerInvoiceNotice(int invoiceid) {

        TaxerInvoice invoice = new TaxerInvoice().selectById(invoiceid);
        if (invoice == null) return false;

        Maker maker = new Maker().selectById(invoice.getUserid());

        if (maker == null) return false;
        MakerAccount account = new MakerAccount().selectOne(Condition.create().eq("userid", maker.getUserid()));
        if (null == account) return false;

        String openid = maker.getTaxerOpenid();

		/*
		{{first.DATA}}
		发票抬头：{{keyword1.DATA}}
		开票金额：{{keyword2.DATA}}
		发票类型：{{keyword3.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(INVOICE_NOTIFY_TEMPLATE);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of("发票开具成功通知", "#000000"));
        data.put("thing4", WxTempleteMessage.ValueColor.of(invoice.getInvoiceContent()));
        data.put("amount3", WxTempleteMessage.ValueColor.of(NumberUtil.formatFloat2_0(invoice.getAmount().floatValue()) + "元"));
        data.put("thing2", WxTempleteMessage.ValueColor.of(invoice.getCompanyName()));
        message.setData(data);

        sendMessage(message, account.getRealname(), EmailType.TAXER_MAKER, INVOICE_NOTIFY_TEMPLATE, account.getUserid());
        return true;
    }

    @Override
    public boolean notifyUserProjectRefused(int projectid) {

        CompanyProject project = new CompanyProject().selectById(projectid);
        if (project == null) return false;

        Company company = new Company().selectById(project.getCompid());
        if (company == null) return false;

        Integer userid = project.getUserid();
        Maker maker = new Maker().selectById(userid);
        if (maker == null) return false;
        MakerAccount account = new MakerAccount().selectOne(Condition.create().eq("userid", maker.getUserid()));
        if (null == account) return false;
        String openid = maker.getOpenid();
		/*
		标题业务状态变更通知
		行业IT科技 - 互联网|电子商务
		详细内容{{first.DATA}}
		变更类型：{{keyword1.DATA}}
		变更结果：{{keyword2.DATA}}
		变更时间：{{keyword3.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(TEMP_STATE_CHANGED);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of(company.getCompname() + "拒绝验收项目:" + project.getProjectname(), "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of("项目进度更新"));
        data.put("keyword2", WxTempleteMessage.ValueColor.of("企业拒绝验收,\n原因:" + project.getRejectReason()));
        data.put("keyword3", WxTempleteMessage.ValueColor.of(DateUtil.getString(new Date(), DateUtil.FORMAT_STYLE_6)));
        data.put("remark", WxTempleteMessage.ValueColor.of(""));
        message.setData(data);

        sendMessage(message, account.getRealname(), EmailType.MAKER, TEMP_STATE_CHANGED, account.getUserid());
        return true;
    }

    @Override
    public boolean notifyCustomerAgents(int id) {

        String name;

        MakerAccount account = new MakerAccount().selectById(id);
        if (account == null) return false;

        name = "创客 - " + account.getRealname();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("oB8CR0XBgYQ0kKSEbF5JDN2CPiv8", "赵菲");
        hashMap.put("oB8CR0T4k7ND_fPk0HJwpz46FIDU", "梁秋颖");
        hashMap.put("oB8CR0X1MUMgFW3W4heM_MF4UawQ", "谢珊妮");
        notificationConfig.getCustomerAgents().forEach(openid -> {
			/*
			标题认证通知
			行业IT科技 - 互联网|电子商务
			详细内容{{first.DATA}}
			认证详情：{{keyword1.DATA}}
			认证结果：{{keyword2.DATA}}
			{{remark.DATA}}
			*/
            WxTempleteMessage message = new WxTempleteMessage();
            message.setTouser(openid);
            message.setTemplate_id(TEMP_AUTH_NOTIFY);
            Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
            data.put("first", WxTempleteMessage.ValueColor.of("实名认证资料提交通知", "#000000"));
            data.put("keyword1", WxTempleteMessage.ValueColor.of(name));
            data.put("keyword2", WxTempleteMessage.ValueColor.of("资料提交，等待审核"));
            data.put("remark", WxTempleteMessage.ValueColor.of("请尽快审核，谢谢！"));
            message.setData(data);

            sendMessage(message, hashMap.get(openid), EmailType.OTHER, TEMP_AUTH_NOTIFY, null);
        });
        return true;
    }

    @Override
    public boolean notifyCompanyAgents(int id) {

        String name;
        Company company = new Company().selectById(id);
        if (company == null) return false;

        name = "企业 - " + company.getCompname();

        //企业的通知，只发给赵菲
        notificationConfig.getCompanyAgents().forEach(openid -> {

			/*
			标题认证通知
			行业IT科技 - 互联网|电子商务
			详细内容{{first.DATA}}
			认证详情：{{keyword1.DATA}}
			认证结果：{{keyword2.DATA}}
			{{remark.DATA}}
			*/
            WxTempleteMessage message = new WxTempleteMessage();
            message.setTouser(openid);
            message.setTemplate_id(TEMP_AUTH_NOTIFY);
            Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
            data.put("first", WxTempleteMessage.ValueColor.of("实名认证资料提交通知", "#000000"));
            data.put("keyword1", WxTempleteMessage.ValueColor.of(name));
            data.put("keyword2", WxTempleteMessage.ValueColor.of("资料提交，等待审核"));
            data.put("remark", WxTempleteMessage.ValueColor.of("请尽快审核，谢谢！"));
            message.setData(data);

            sendMessage(message, "赵菲", EmailType.OTHER, TEMP_AUTH_NOTIFY, null);
        });

        return true;
    }

    @Override
    public boolean sendPerformanceNotice(PartnerDetailDto partner, int type) {

		/*
		标题业务处理结果通知
		行业IT科技 - 互联网|电子商务
		详细内容{{first.DATA}}
		系统名称：{{keyword1.DATA}}
		完成时间：{{keyword2.DATA}}
		结果描述：{{keyword3.DATA}}
		{{remark.DATA}}
		*/

        String remark = "";
        String realname = partner.getRealname();
        switch (type) {
            case 1: //上个月
                break;
            case 2: //过去2个月
                remark = "过去两个月，合伙人-" + realname + "成功推荐客户0个";
                break;

            case 3: //过去3个月
                remark = "过去一个季度，合伙人-" + realname + "成功推荐客户0个";
                break;
            default:

                break;
        }

        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(notificationConfig.getBossOpenid());
        message.setTemplate_id(TEMP_SEND_NOTICE);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of(" 平台季度业绩公告", "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of(realname));
        data.put("keyword2", WxTempleteMessage.ValueColor.of(DateUtil.getString(partner.getEffectivedate(), DateUtil.FORMAT_STYLE_2)));
        data.put("keyword3", WxTempleteMessage.ValueColor.of("季度业绩不良"));
        data.put("remark", WxTempleteMessage.ValueColor.of(remark));
        message.setData(data);

        sendMessage(message, realname, EmailType.OTHER, TEMP_SEND_NOTICE, null);
        return true;
    }

    @Override
    public boolean sendSurveyNotice(String title, String content, String url, String openid) {
		/*

		模版ID：vKSV5smmI5h9zd4mxRyIVyu4FMqqCQJu1MyEwso7gZs
				开发者调用模版消息接口时需提供模版ID
		标题问卷接收成功通知
		行业IT科技 - 互联网|电子商务
		详细内容{{first.DATA}}
		问卷主题：{{keyword1.DATA}}
		发起时间：{{keyword2.DATA}}
		结束时间：{{keyword3.DATA}}
		{{remark.DATA}}
		*/

        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(TEMP_SURVEY_NOTICE);
        message.setUrl(url);

        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of(title, "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of(content));
        data.put("keyword2", WxTempleteMessage.ValueColor.of(DateUtil.getString(new Date())));
        data.put("keyword3", WxTempleteMessage.ValueColor.of("无"));
        data.put("remark", WxTempleteMessage.ValueColor.of(""));
        message.setData(data);

        sendMessage(message, null, null, TEMP_SURVEY_NOTICE, null);
        return true;
    }

    /**
     * 给智杰祱公众号的创客发送文字公告
     *
     * @param title  标题
     * @param url    链接
     * @param openid openid
     * @return true
     */
    public boolean sendTaxerNotice(String title, String url, String openid) {

		/*
		标题业务处理结果通知
		行业IT科技 - 互联网|电子商务
		详细内容{{first.DATA}}
		系统名称：{{keyword1.DATA}}
		完成时间：{{keyword2.DATA}}
		结果描述：{{keyword3.DATA}}
		{{remark.DATA}}
		*/
        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(TEMP_HANDLE);
        message.setUrl(url);
        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of(" 平台公告", "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of(title));
        data.put("keyword2", WxTempleteMessage.ValueColor.of(DateUtil.getNowTimeString()));
        data.put("keyword3", WxTempleteMessage.ValueColor.of("请点击查看详情"));
        message.setData(data);

        sendMessage(message, null, null, TEMP_HANDLE, null);
        return true;
    }

    /**
     * 给智杰祱的创客发送问卷调查公告
     *
     * @param title   标题
     * @param content 内容
     * @param url     链接
     * @param openid  openid
     * @return true
     */
    public boolean sendTaxerSurveyNotice(String title, String content, String url, String openid) {
		/*

		模版ID：0dncQ9-PEV5m-mIZ648G1qZyD2NNll7rkJ0tbvLqjFg
				开发者调用模版消息接口时需提供模版ID
		标题问卷接收成功通知
		行业IT科技 - 互联网|电子商务
		详细内容{{first.DATA}}
		问卷主题：{{keyword1.DATA}}
		发起时间：{{keyword2.DATA}}
		结束时间：{{keyword3.DATA}}
		{{remark.DATA}}
		*/

        WxTempleteMessage message = new WxTempleteMessage();
        message.setTouser(openid);
        message.setTemplate_id(TEMP_QUESTIONNAIRE);
        message.setUrl(url);

        Map<String, WxTempleteMessage.ValueColor> data = new HashMap<>();
        data.put("first", WxTempleteMessage.ValueColor.of(title, "#000000"));
        data.put("keyword1", WxTempleteMessage.ValueColor.of(content));
        data.put("keyword2", WxTempleteMessage.ValueColor.of(DateUtil.getString(new Date())));
        data.put("keyword3", WxTempleteMessage.ValueColor.of("无"));
        data.put("remark", WxTempleteMessage.ValueColor.of(""));
        message.setData(data);
        sendMessage(message, null, null, TEMP_QUESTIONNAIRE, null);
        return true;
    }
}
